package com.onLineCar.manages.aspect.config;

import cn.hutool.core.date.StopWatch;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @projectName: tlias-backend - login
 * @package: com.itheima.aspect
 * @className: OperateLogAspect
 * @author: YuZequan
 * @date: 2023/7/19 16:12
 */
@Aspect
@Component
@Slf4j
public class OperateLogAspect {
    @Autowired
    private HttpServletRequest request;

    public static final String USER_NAME_STR = "username";

    public static ThreadLocal<String> userNameThreadLocal = new ThreadLocal<>();

    /*定义切点*/

    @Pointcut("execution(* com.onLineCar.manages.web.*.*(..))")
    public void pt() {

    }


    @Around("pt()")
    public Object record(ProceedingJoinPoint joinPoint) throws Throwable {
        // 1. 操作人
        if (ObjectUtils.isNotEmpty(request.getCookies())) {
            Arrays.stream(request.getCookies())
                    .forEach(cookie -> {

                        if (ObjectUtils.isNotEmpty(cookie) & cookie.getName().equals(USER_NAME_STR)) {
                            userNameThreadLocal.set(cookie.getValue());
                        }
                    });
        } else {
            userNameThreadLocal.set("未知");
        }

        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Object result = joinPoint.proceed();
        stopWatch.stop();
        log.info("----------->start<------");
        log.info("类------>{}<------------", className);
        log.info("方法---->{}<-------------", methodName);
        log.info("入参---->{}<-------------", args);
        log.info("执行时间->{}ms<-----------", stopWatch.getTotalTimeMillis());
        log.info("----------->end<--------");
        return result;
    }

}
